package org.yunai.yfserver.util;

import org.jumpmind.symmetric.csv.CsvReader;
import org.jumpmind.symmetric.csv.CsvWriter;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * CsvReader工具类
 * User: yunai
 * Date: 13-1-4
 * Time: 下午11:25
 */
public class CsvUtil {

    private static Charset defaultCharset = Charset.forName("UTF-8");

    public static CsvReader createReader(String csvPath) throws FileNotFoundException {
        URL url = Thread.currentThread().getContextClassLoader().getResource(csvPath);
        assert url != null;
        return new CsvReader(url.getFile(), ',', defaultCharset);
    }

    public static CsvWriter createSysWriter(String csvSysPath) {
        return new CsvWriter(csvSysPath, ',', defaultCharset);
    }

    public static int getInt(CsvReader reader, String key, int defaultVal) throws IOException {
        String val = reader.get(key);
        return !StringUtils.isEmpty(val) ? Integer.valueOf(val) : defaultVal;
    }

    public static short getShort(CsvReader reader, String key, short defaultVal) throws IOException {
        String val = reader.get(key);
        return val != null ? Short.valueOf(val) : defaultVal;
    }

    public static double getDouble(CsvReader reader, String key, double defaultVal) throws IOException {
        String val = reader.get(key);
        return val != null ? Double.valueOf(val) : defaultVal;
    }

    public static String getString(CsvReader reader, String key, String defaultVal) throws IOException {
        String val = reader.get(key);
        return val != null ? val : defaultVal;
    }
}
